//
//  RegisterVC.swift
//  YunshuApp
//
//  Created by 周文杰 on 2017/5/10.
//  Copyright © 2017年 zwj. All rights reserved.
//

import UIKit

class RegisterVC: UIViewController , UIKeyboardViewControllerDelegate{

    let contentView = UIScrollView.init(frame: CGRect.init(x: 0, y: 0, width: Const.SCREEN_WIDTH, height: Const.SCREEN_HEIGHT))

    let phone = UITextField.init(frame: CGRect.init(x: 90, y: 5, width: Const.SCREEN_WIDTH - 190 , height: 40))
    let btn = UIButton.init(frame: CGRect.init(x: Const.SCREEN_WIDTH - 100, y: 0, width: 90, height: 50))
    
    let verifyCode = UITextField.init(frame: CGRect.init(x: 90, y: 10, width: Const.SCREEN_WIDTH - 100 , height: 30))
    
    let password = UITextField.init(frame: CGRect.init(x: 90, y: 10, width: Const.SCREEN_WIDTH - 100 , height: 30))
    
    let name = UITextField.init(frame: CGRect.init(x: 90, y: 10, width: Const.SCREEN_WIDTH - 100 , height: 30))
    
    let company = UITextField.init(frame: CGRect.init(x: 90, y: 10, width: Const.SCREEN_WIDTH - 100 , height: 30))
    
    let business = UITextField.init(frame: CGRect.init(x: 90, y: 10, width: Const.SCREEN_WIDTH - 100 , height: 30))
    
    var _timer : Timer?
    var time = 60
    var keyboard:UIKeyboardViewController?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        self.view.addSubview(contentView)
        self.title = "注册"
        
        self.addPhone()
        self.addItem("验证码", value: verifyCode, placeholder: "输入验证码")
        self.addItem("密码", value: password, placeholder: "请设置密码")
        self.addItem("姓名", value: name, placeholder: "请输入姓名")
        self.addItem("公司", value: company, placeholder: "请输入公司名称")
        self.addItem("主营业务", value: business, placeholder: "请输入公司主营业务")
        
        let btn = UIButton.init(type: .roundedRect)
        btn.frame = CGRect.init(x: 10, y: 0, width: Const.SCREEN_WIDTH - 20, height: 44)
        btn.backgroundColor = Const.WTM_GREEN
        btn.setTitle("注册", for: .normal)
        btn.tag = 99
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.addTarget(self, action: #selector(RegisterVC.submit), for: .touchUpInside)
        self.contentView.addSubview(btn)
    
        self.addKeyboardToolbar()
        
        self.view.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(RegisterVC.onTap)))

    }
    
    @objc func onTap() {
        self.phone.resignFirstResponder()
        self.verifyCode.resignFirstResponder()
        self.password.resignFirstResponder()
        self.name.resignFirstResponder()
        self.company.resignFirstResponder()
        self.business.resignFirstResponder()
    }
    
    func addKeyboardToolbar() -> Void {
        keyboard = UIKeyboardViewController.init(controllerDelegate: self)
        keyboard?.tabbarHeight  = 0;
        //        keyboard?.boardDelegate = self;
        keyboard?.addToolbarToKeyboard()
    }


    func  addPhone() -> Void {
        let container = UIView.init(frame: CGRect.init(x: 0, y: 0, width: Const.SCREEN_WIDTH, height: 50))
        let nameLabel = UILabel.init(frame: CGRect.init(x: 10, y: 0, width: 80, height: 50))
        nameLabel.text = "手机号"
        container.addSubview(nameLabel)
        
        phone.placeholder = "输入手机号"
        phone.layer.borderColor = Const.WTM_GRAY.cgColor
        phone.layer.borderWidth = 0.5
        phone.layer.cornerRadius = 5
        container.addSubview(phone)
        
        
        btn.setTitle("获取验证码", for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        btn.setTitleColor(UIColor.red, for: .normal)
        btn.addTarget(self, action: #selector(RegisterVC.sendVerifyCode), for: .touchUpInside)
        container.addSubview(btn)
        container.tag = 99

        self.contentView.addSubview(container)
    }

    func  addItem(_ name:String, value:UITextField, placeholder:String) -> Void {
        let container = UIView.init(frame: CGRect.init(x: 0, y: 0, width: Const.SCREEN_WIDTH, height: 50))
        let nameLabel = UILabel.init(frame: CGRect.init(x: 10, y: 0, width: 80, height: 50))
        nameLabel.text = name
        container.addSubview(nameLabel)
        
        value.placeholder = placeholder
        value.layer.borderColor = Const.WTM_GRAY.cgColor
        value.layer.borderWidth = 0.5
        value.layer.cornerRadius = 5
        value.frame = CGRect.init(x: 90, y: 5, width: Const.SCREEN_WIDTH - 100 , height: 40)
        container.addSubview(value)
        
        container.tag = 99
        self.contentView.addSubview(container)
    }

    
    @objc func sendVerifyCode() {
        let tel = phone.text
        if (tel == nil || tel?.count == 0){
            self.navigationController?.view.makeToast(phone.placeholder!);
            return
        }
        _ = NetworkManager.GET(NetworkManager.SEND_CODE,params:["phone":tel!]) { (isSuccess, resp) in
            if isSuccess {
                self.navigationController?.view.makeToast("验证码发送成功");

                self.disableBtn()
            }
        }
    }
    
    func disableBtn() -> Void {
        let interVal : TimeInterval = 1
        time = 60
        btn.isEnabled = false
        _timer = Timer.scheduledTimer(timeInterval: interVal, target: self, selector: #selector(RegisterVC.updateBtn), userInfo: nil, repeats: true)
        //        _timer?.fire()
        RunLoop.current.add(_timer!, forMode: RunLoop.Mode.common)
    }
    @objc  
    func updateBtn() {
        
        time -= 1
        
        if time < 0 {
            DispatchQueue.main.async {
                
                self.btn.setTitle( "重新发送", for: .normal)
                self.btn.isEnabled = true
                
                guard let timer1 = self._timer else{
                    return
                }
                timer1.invalidate()
            }
        }else {
            DispatchQueue.main.async {
                
                self.btn.setTitle( "\(self.time)s", for: .disabled)
            }
        }
    }
    
    @objc func submit() {
        
        let fields = [phone,verifyCode,name,company,business]
        for field in fields {
            if field.text == nil || field.text?.count == 0 {
                self.navigationController?.view.makeToast(field.placeholder!)
                return
            }
        }
        
        let params = ["phone":phone.text! ,
                      "code":verifyCode.text! ,
            "password" : password.text! ,
            "nickname" : name.text! ,
            "company" : company.text! ,
            "mainbusiness" : business.text!,
            "wx" : "0"]
        _ = NetworkManager.GET(NetworkManager.REGISTER,params:params) { (isSuccess, resp) in
            if isSuccess {
                
                let alert = UIAlertController(title: "提示", message:"恭喜你，注册成功！", preferredStyle: UIAlertController.Style.alert)
                let action = UIAlertAction.init(title: "我知道了", style: .cancel, handler: { (action1) in
                    self.navigationController?.popViewController(animated: true)
                })
                alert.addAction(action)
                self.navigationController?.present(alert, animated: true, completion: nil)
            }
        }
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        var y:CGFloat = 20
        for iView in contentView.subviews {
            if iView.tag == 99 {
                var frame = iView.frame
                frame.origin.y = y
                y += frame.size.height + 10
                iView.frame = frame
            }
        }
        
        self.contentView.contentSize = CGSize.init(width: Const.SCREEN_WIDTH, height: y + 20)
    }
}
